﻿namespace Digitalmes.Application.Common.Models;

/// <summary>
/// API 接口返回结果。
/// </summary>
public sealed class ApiResult<TData> : IApiResult<TData>, IApiResult
{
    public int Code { get; init; }

    [NotNull]
    public string? Message { get; init; }

    public TData? Data { get; init; }

    object? IApiResult.Data => Data;
}

/// <summary>
/// API 接口返回结果。
/// </summary>
public sealed class ApiResult : IApiResult
{
    /// <summary>
    /// OK 状态码
    /// </summary>
    internal const int SuccessCode = 200;

    /// <summary>
    /// Bad 状态码
    /// </summary>
    internal const int BadCode = -1;

    public int Code { get; init; }

    [NotNull]
    public string? Message { get; init; }

    public object? Data { get; init; }

    #region 工厂对象

    /// <summary>
    /// 返回成功结果，状态码 200。
    /// </summary>
    /// <param name="data">数据</param>
    /// <returns></returns>
    public static IApiResult Ok(object? data = null)
    {
        return new ApiResult()
        {
            Code = SuccessCode,
            Message = string.Empty,
            Data = data,
        };
    }

    /// <summary>
    /// 返回成功结果，状态码 200。
    /// </summary>
    /// <typeparam name="TData"></typeparam>
    /// <param name="data">数据</param>
    /// <returns></returns>
    public static IApiResult<TData> Ok<TData>(TData? data)
    {
        return new ApiResult<TData>()
        {
            Code = SuccessCode,
            Message = string.Empty,
            Data = data,
        };
    }

    /// <summary>
    /// 返回失败结果，状态码 -1。
    /// </summary>
    /// <param name="message">错误原因</param>
    /// <returns></returns>
    public static IApiResult Bad(string? message = null)
    {
        return new ApiResult()
        {
            Code = BadCode,
            Message = message ?? string.Empty,
        };
    }

    /// <summary>
    /// 返回失败结果
    /// </summary>
    /// <param name="code">错误状态码</param>
    /// <param name="message">错误原因</param>
    /// <returns></returns>
    public static IApiResult Bad(int code, string? message = null)
    {
        return new ApiResult()
        {
            Code = code,
            Message = message ?? string.Empty,
        };
    }

    #endregion
}
